<template>
    <view class="booking-list">
        <!-- 使用v-for循环渲染预约记录 -->
        <view class="booking-list-item" v-for="(item, index) in bookingRecords" :key="item.id">
            <view class="booking-header">
                <text class="booking-title">
                    {{item.courseName}}
                </text>
                <!-- 根据状态显示不同颜色 -->
                <view class="booking-status" :style="{ backgroundColor: getStatusColor(item.status) }">
                    {{getStatusText(item.status)}}
                </view>
            </view>
            <view class="booking-details">
                <text>
                    预约时间：
                </text>
                {{formatDateTime(item.bookedAt)}}
            </view>
            <view class="booking-details">
                <text>
                    课程时间：
                </text>
                {{formatDateTime(item.startTime)}} - {{formatTime(item.endTime)}}
            </view>
            <view class="booking-details">
                <text>
                    课程ID：
                </text>
                {{item.courseId}}
            </view>

            <!-- 仅当状态为"已预约"或"待进行"时显示取消按钮 -->
            <view class="btn" v-if="['booked', 'pending'].includes(item.status)" @click="cancelBooking(item.courseId)">
                取消预约
            </view>
        </view>
        
        <!-- 无数据提示 -->
        <view class="no-data" v-if="bookingRecords.length === 0">
            <text>暂无预约记录</text>
        </view>
    </view>
</template>

<script>
    import {
        getToken
    } from '@/utils/auth.js';
    export default {
        data() {
            return {
                bookingRecords: [] // 存储预约记录
            }
        },
        onLoad() {
            this.BookingThisWeek();
        },
        methods: {
            // 预约课程记录
            BookingThisWeek() {
                let data = {
                    openid: getToken()
                }

                this.request('gym/Booking/thisWeek', data, 'GET').then(res => {
                    console.log("预约课程记录----", res);
                    
                    if (res && res.code === 200 && res.data) {
                        // 将API返回的数据保存到bookingRecords
                        this.bookingRecords = res.data;
                    } else {
                        // 显示错误提示
                        uni.showToast({
                            title: '获取预约记录失败',
                            icon: 'none'
                        });
                    }
                }).catch(err => {
                    console.error('请求发生错误:', err);
                    uni.showToast({
                        title: '网络请求失败',
                        icon: 'none'
                    });
                });
            },
            
            // 根据状态获取显示文本
            getStatusText(status) {
                const statusMap = {
                    'booked': '已预约',
                    'cancelled': '已取消',
                    'pending': '待进行',
                    'ongoing': '进行中',
                    'completed': '已完成'
                };
                
                return statusMap[status] || status;
            },
            
            // 根据状态获取显示颜色
            getStatusColor(status) {
                const colorMap = {
                    'booked': '#4CAF50',    // 绿色
                    'pending': '#4CAF50',   // 绿色
                    'ongoing': '#2196F3',   // 蓝色
                    'completed': '#777',    // 灰色
                    'cancelled': '#f44336'  // 红色
                };
                
                return colorMap[status] || '#4CAF50';
            },
            
            // 格式化日期时间为 'YYYY-MM-DD HH:MM' 格式
            formatDateTime(dateTimeStr) {
                if (!dateTimeStr) return '';
                
                const date = new Date(dateTimeStr);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                
                return `${year}-${month}-${day} ${hours}:${minutes}`;
            },
            
            // 格式化时间为 'HH:MM' 格式
            formatTime(dateTimeStr) {
                if (!dateTimeStr) return '';
                
                const date = new Date(dateTimeStr);
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                
                return `${hours}:${minutes}`;
            },
            
            // 取消预约
            cancelBooking(bookingId) {
                uni.showModal({
                    title: '取消预约',
                    content: '确定要取消此预约吗？',
                    success: (res) => {
                        if (res.confirm) {
                            // 用户点击确定，发送取消请求
                            this.doCancelBooking(bookingId);
                        }
                    }
                });
            },
            
            // 执行取消预约的API请求
            doCancelBooking(bookingId) {
                uni.showLoading({
                    title: '取消中...'
                });
                
                const data = {
                    openid: getToken(),
                    id: bookingId
                };
                
                this.request('gym/Reserve/delectThisWeek', data, 'GET').then(res => {
                    uni.hideLoading();
                    
                    if (res && res.code === 200) {
                        uni.showToast({
                            title: '取消成功',
                            icon: 'success'
                        });
                        
                        // 刷新预约列表
                        this.BookingThisWeek();
                    } else {
                        uni.showToast({
                            title: res?.msg || '取消失败',
                            icon: 'none'
                        });
                    }
                }).catch(err => {
                    uni.hideLoading();
                    console.error('请求发生错误:', err);
                    
                    uni.showToast({
                        title: '网络请求失败',
                        icon: 'none'
                    });
                });
            }
        }
    }
</script>

<style lang="scss">
    @import '@/common/mixins.scss';

    // @include rounded-box(32upx);
    // @include box-sizing-padding(24upx);
    // @include flex-center(center, space-between, column);
    .btn {
        width: 160rpx;
        height: 70rpx;
        @include rounded-box(10rpx, #d9534f);
        @include flex-center();
        font-size: 30rpx;
        font-weight: bold;
        color: #fff;
        margin-top: 20rpx;
    }

    .booking-details {
        width: 100%;
        font-size: 28rpx;
        color: #fff;
        @include flex-center(center, left);
        margin-bottom: 10rpx;

        text {
            font-size: 30rpx;
            color: #aaa;
            font-weight: bold;
        }
    }

    .booking-header {
        width: 100%;
        height: 80rpx;
        @include flex-center(center, space-between);
        margin-bottom: 15rpx;

        .booking-title {
            font-size: 34rpx;
            color: #FFD700;
            font-weight: bold;
            border-bottom: 2px solid #FFD700;
            padding: 10rpx 0;
        }

        .booking-status {
            font-size: 28rpx;
            padding: 6rpx 16rpx;
            border-radius: 8rpx;
            font-weight: bold;
            color: #fff;
            @include flex-center();
        }
    }


    .booking-list {
        width: 680rpx;
        min-height: 100vh;
        margin: 30rpx auto;
        @include flex-center(center, top, column);

        .booking-list-item {
            width: 100%;
            min-height: 300rpx;
            border: 2rpx solid #444;
            @include rounded-box(16rpx, #2c2c2c);
            @include box-sizing-padding(20rpx);
            margin-bottom: 30rpx;
        }
    }
    
    .no-data {
        width: 100%;
        height: 200rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #999;
        font-size: 28rpx;
    }
</style>